//
//  BHHTTPClient.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/12.
//

import UIKit
import Alamofire

class BHHTTPClient {
    
    func get(url: String, paramters: [String: Any]?, handler: @escaping (Bool,String,Dictionary<String,Any>) -> Void) {
        let getUrl = self.append(url: url, dic: paramters).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        self.comService(method: .get, url: getUrl!, paramters: nil) { (result, message, dic) in
            handler(result,message,dic)
        }
    }
    
    
    func post(url: String, paramters: [String: Any]?,handler: @escaping (Bool,String,Dictionary<String,Any>) -> Void) {
        self.comService(method: .post, url: url, paramters: paramters) { (result, message, dic) in
            handler(result,message,dic)
        }
    }
    
    func delete(url: String, paramters: [String: Any]?,handler: @escaping (Bool,String,Dictionary<String,Any>) -> Void) {
        let getUrl = self.append(url: url, dic: paramters).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        self.comService(method: .delete, url: getUrl!, paramters: paramters) { (result, message, dic) in
            handler(result,message,dic)
        }
    }
    
    
    func put(url: String, paramters: [String: Any]?,handler: @escaping (Bool,String,Dictionary<String,Any>) -> Void) {
        self.comService(method: .put, url: url, paramters: paramters) { (result, message, dic) in
            handler(result,message,dic)
        }
    }
    
}


// MARK: 普通请求
extension BHHTTPClient {
    
    private func comService(method: HTTPMethod, url: String, paramters: [String: Any]?, handler: @escaping (Bool,String,Dictionary<String,Any>) -> Void) {
//        if BHHTTPNetStateManager.shared.linkState == 0 { // 没网
//            handler(false,String.netConnectError,[:])
//            return
//        }
        
        let requestUrl = BHHTTPUrl.url(url: url)
        let manager = Alamofire.Session.default
        manager.sessionConfiguration.timeoutIntervalForRequest = 15
        manager.request(requestUrl, method: method,parameters: paramters,encoding: JSONEncoding.default,headers: BHHTTPHeader.header).responseJSON { (response) in
            print("接口： \(requestUrl) 返参：\(response)")

            if response.value == nil {
                handler(false,String.netConnectError,[:])
            }else {

                let dic = response.value as? Dictionary<String,Any>
                if dic == nil {
                    handler(false,String.serviceResponseError,[:])
                }else {
                    let success = BHJsonTool.decodeIntFromDic(dic: dic!, key: "success")
                    if success == 1 {
                        let code = BHJsonTool.decodeIntFromDic(dic: dic!, key: "code")
                        if code == 200 {
                            handler(true,"",dic!)
                        }else {
                            let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                            handler(false,message,dic!)
                        }
                    }else {
                        let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                        handler(false,message,dic!)
                    }
                }
            }
        }
    }
}

extension BHHTTPClient {
    func append(url: String, dic: [String: Any]?) -> String {
        if dic == nil {
            return url
        }else {
            var tempUrl = url
            for (key,value) in dic! {
                if tempUrl.contains("?") == false {
                    tempUrl.append("?\(key)=\(value)")
                }else {
                    tempUrl.append("&\(key)=\(value)")
                }
            }
            return tempUrl
        }
    }
}
// MARK: 上传图片
extension BHHTTPClient {
    
    func upload(images: [UIImage],progressHandler: ((Double) -> Void)?, handler: @escaping (Bool,String,[String]) -> Void)  {
//        if BHHTTPNetStateManager.shared.linkState == 0 { // 没网
//            progressHandler?(0.0)
//            handler(false,String.netConnectError,[])
//            return
//        }
        
        let requestUrl = BHHTTPUrl.url(url: String.common_upload_url)
        let manager = Alamofire.Session.default
        manager.upload(multipartFormData: { (formata) in
            for (index,image) in images.enumerated() {
                let data = image.jpegData(compressionQuality: 0.5)!
                let imageName = NSDate.currentTimeValue()+"\(index).jpg"
                formata.append(data, withName: "fileList", fileName: imageName, mimeType: "image/jpeg")
            }
            
        }, to: requestUrl,method: .post,headers: BHHTTPHeader.header).uploadProgress(queue: DispatchQueue.main) { (progress) in
            progressHandler?(progress.fractionCompleted)
        }.responseJSON { (response) in
            let dic = response.value as? Dictionary<String,Any>
            if dic == nil {
                handler(false,String.serviceResponseError,[])
            }else {
                let success = BHJsonTool.decodeIntFromDic(dic: dic!, key: "success")
                if success == 1 {
                    let code = BHJsonTool.decodeIntFromDic(dic: dic!, key: "code")
                    if code == 200 {
                        let result = BHJsonTool.decodeArrayFromDic(dic: dic!, key: "result")
                        var temp: [String] = []
                        for item in result {
                            if item is NSNull {
                                continue
                            }else {
                                temp.append(item as! String)
                            }
                        }
                        handler(true,"",temp)
                    }else {
                        let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                        handler(false,message,[])
                    }
                }else {
                    let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                    handler(false,message,[])
                }
            }
        }
        
    }
}


//MARK: 上传视频
extension BHHTTPClient {
    func uploadVideo(data: Data,progressHandler: ((Double) -> Void)?, handler: @escaping (Bool,String,String,String) -> Void) {
//        if BHHTTPNetStateManager.shared.linkState == 0 { // 没网
//            progressHandler?(0.0)
//            handler(false,String.netConnectError,"","")
//            return
//        }
        
        let requestUrl = BHHTTPUrl.url(url: String.common_uploadVideo_url)
        let manager = Alamofire.Session.default
        manager.upload(multipartFormData: { (formata) in
            let videoName = NSDate.currentTimeValue()+"_video.mp4"
            formata.append(data, withName: "file", fileName: videoName, mimeType: ".mp4")
            
        }, to: requestUrl,method: .post,headers: BHHTTPHeader.header).uploadProgress(queue: DispatchQueue.main) { (progress) in
            progressHandler?(progress.fractionCompleted)
        }.responseJSON { (response) in
            let dic = response.value as? Dictionary<String,Any>
            if dic == nil {
                handler(false,String.serviceResponseError,"","")
            }else {
                let success = BHJsonTool.decodeIntFromDic(dic: dic!, key: "success")
                if success == 1 {
                    let code = BHJsonTool.decodeIntFromDic(dic: dic!, key: "code")
                    if code == 200 {
                        let result = BHJsonTool.decodeDicFromDic(dic: dic!, key: "result")
                        let videoUrl = BHJsonTool.decodeStringFromDic(dic: result, key: "url")
                        let cover = BHJsonTool.decodeStringFromDic(dic: result, key: "frame")
                        
                        handler(true,"",videoUrl,cover)
                    }else {
                        let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                        handler(false,message,"","")
                    }
                }else {
                    let message = BHJsonTool.decodeStringFromDic(dic: dic!, key: "message")
                    handler(false,message,"","")
                }
            }
        }
        
    }
}
